'use strict';
var router = require('express').Router();
var AV = require('leanengine');
var request = require('request');
var session = require('express-session');
var crypto = require('crypto');
var async = require('async');
var prize=require('../server-modules/Prize');

//微信跳转页面
router.get('/weChat_login', function (req, res) {
    res.render('weChat_login', {});
});

//得到微信Id
router.get('/jumpPage', function (req, res) {
    var data=aesDecode(req.query.body);
    //var data = req.query.body;
    console.log('对收到req.query.body进行解密----');
    var body = JSON.parse(data);
    console.log('更改成json----');
    req.session.body = body;
    var wechatInfo = req.session.body;
    console.log('有用户微信登录进来----' + wechatInfo.nickname);
    console.log('用户的openid为----' + wechatInfo.openid);
    //检查数据库是否存在此用户
    async.series([function(cb){
        var query = new AV.Query('User_Name');
        query.equalTo('openId', body.openid);
        query.first().then(function (User) {
            if (User) {
                //存在此用户
                console.log('存在此用户');
                wechatInfo.userId = User.id;
                console.log('此用户User_ID为----' + wechatInfo.userId);
                cb()
            } else {
                //不存在此用户
                console.log('不存在此用户');
                var Todo = new AV.Object('User_Name');
                Todo.set('openId', body.openid);
                Todo.set('nickName', body.nickname);
                Todo.set('headImgurl', body.headimgurl);
                Todo.save().then(function (User) {
                    wechatInfo.userId = User.id;
                    console.log('向数据库存储此用户,User_ID为----' + wechatInfo.userId);
                    cb()
                }, function (error) {
                    console.log(error);
                    cb(error)
                })
            }
        }, function (error) {
            console.log(error);
            cb(error)
        });
    },function(cb){
        var query = new AV.Query('User_Name');
        query.count().then(function(Total){
            //拿到此用户信息,并在页面展示
            res.render('jumpPage', {
                Total:Total+1000
            });
        },function(error){
            console.log(error);
        });
        cb()
    }],function(error,results){})
});

//进入排行榜页面
router.get('/rankingList', function (req, res) {
    var query = new AV.Query('Winning_Record');
    query.find().then(function(results) {
        res.render('rankingList', {
            results:results,
            index:'1'
        });
    }, function(err) {
        console.log(err)
    });
});

//进入专区到品牌页面
router.get('/personal', function (req, res) {
    //拿到session
    var wechatInfo = req.session.body;
    console.log(wechatInfo.openid);
    res.render('personal', {
        openId: wechatInfo.openid,
        nickName: wechatInfo.nickname,
        headImgurl: wechatInfo.headimgurl,
        UserId: wechatInfo.userId
    });
});

//进入游戏页面
router.get('/game', function(req, res, next) {
    var wechatInfo = req.session.body;
    var objectId = wechatInfo.userId;
    var query = new AV.Query('User_Name');
    query.equalTo('objectId',objectId );
    query.first().then(function (data) {
        req.session.user = data;
        var user = req.session.user;
        res.render('game', {
            frequency: user.get('frequency')
        });
    },function(error){
        console.log(error);
    });
});

//游戏次数接口
router.get('/game/frequency', function(req, res, next) {
    var user = req.session.user;
    console.log(req.query.gradient);
    if(req.query.gradient == '1'){
        var Todo = AV.Object.createWithoutData('User_Name',user.objectId);
        var gradient = (user.frequency) - 1;
        user.frequency = (user.frequency) - 1;
        Todo.set('frequency', gradient);
        Todo.save().then(function (User) {
            req.session.User = User;
            prize.getPrizeByUserID('',function(err,Res){
                //抽到的奖品剩余数量-1
                var modify = AV.Object.createWithoutData('Prize', Res.get('id'));
                modify.set('remain_num', Res.get('remain_num') - 1);
                modify.save();
                //在奖品记录表中记录抽到奖品的这个记录
                var query = AV.Object('Winning_Record');
                query.set('Prize_Name', Res.get('Prize_Name'));

                query.set('Prize_Id', Res.get('id'));

                var User = req.session.user;

                console.log(User);
                query.set('User_Id', req.session.User.get('id'));
                query.set('User_Name', User.nickName);
                query.save().then(function(todo) {
                    //返回
                    res.json({
                        frequency:req.session.User.get('frequency'),
                        Prize:Res.get("Prize_Name")
                    });
                },function(error){
                    console.log(error)
                });
            });
        }, function (error) {
            console.log(error)
        });
    }else if(req.query.gradient == '2'){
        //微信分享后增加五次机会
        console.log(req.query.gradient);
        if(user.share){
            var Todo = AV.Object.createWithoutData('User_Name',user.objectId);
            var gradient = (user.frequency) + 5;
            user.frequency = (user.frequency) + 5;
            Todo.set('frequency', gradient);
            Todo.set('share', false);
            Todo.save().then(function (User) {
                req.session.user = User;
                res.json({
                    code:'100',
                    frequency:User.get('frequency')
                })
            }, function (error) {
                console.log(error)
            });
        }else {
            res.json({
                code:'101',
                error:'今天已经分享过了'
            })
        }

    }
});

//薄冰用户授权
router.get('/accreditPage_bobing',function(req,res){
    console.log('code----' + req.query.code);
    var appId='wxf0a5ed9ca275cb0f';//公众号wx084c661043c5d093
    var AppSecret='518230457b7daae9cee7494e7db4886a';
    var url= 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='+appId+'&secret='+AppSecret+'&code='+req.query.code+'&grant_type=authorization_code';
    //var url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='+appId+'&redirect_uri='+redirect_uri+'&response_type='+response_type+'&scope='+scope+'&state='+state+'#wechat_redirect';
    request(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var accessTokenJson=JSON.parse(body);
            console.log('body1' + accessTokenJson.access_token + 'body1' +accessTokenJson.openid)
            //获取授权后的用户信息
            var getInfo_url='https://api.weixin.qq.com/sns/userinfo?access_token='+accessTokenJson.access_token+'&openid='+accessTokenJson.openid+'&lang=zh_CN';
            request(getInfo_url,function(error,response,body){
                if (!error && response.statusCode == 200) {
                    //var result=JSON.parse(body);
                    //console.log(body);
                    // res.send(body);
                    res.redirect('http://wxt.houke.net.cn/moonCakeBetting/personal?body='+body);
                }else {
                    console.log(error)
                }
            });
        }
    });
});

//解密
function aesDecode(data){
    var algorithm = 'aes-128-ecb';
    var key = 'zhuhaozhuhaozhuh';//必须16位

    var buf = new Buffer(key);
    var keyBuffer = buf.toString("binary");
    var clearEncoding = 'utf8';
    var iv = "";
    var ivBuf = new Buffer(iv);
    var ivBuffer = ivBuf.toString("binary");

    var cipherEncoding = 'base64';
    var decipher = crypto.createDecipheriv(algorithm, keyBuffer, ivBuffer);
    var plainChunks = [];
    var cipherChunks = data.split('%');
    for (var i = 0; i < cipherChunks.length; i++) {
        plainChunks.push(decipher.update(cipherChunks[i], cipherEncoding, clearEncoding));
    }
    plainChunks.push(decipher.final(clearEncoding));
    //console.log("UTF8 plaintext deciphered: " + plainChunks.join(''));
    return plainChunks.join('');
}

module.exports = router;